#include <cassert>
#include "Ball.hpp"
#include "PhysicWorld.hpp"
#include "Platform.hpp"
#include "Camera.hpp"


Ball::Ball(sf::Vector2f startPos):
Entity(),
m_obj(),
m_shape(3.f),
m_canJump(false)
{
    // init graphic m_shape
    m_shape.setFillColor(sf::Color::Red);
    m_shape.setOutlineThickness(1.f);
    m_shape.setOutlineColor(sf::Color::Black);
    m_shape.setOrigin(3.f,3.f);
    
    // init physic body
    json::Object o;
    o["type"] = json::String("dynamic");
    o["angle"] = json::Number(0);
    o["position"]["x"] = json::Number(startPos.x);
    o["position"]["y"] = json::Number(-startPos.y);
    o["fixedRotation"] = json::Boolean(false);
    o["bullet"] = json::Boolean(false);
    o["fixtures"] = json::Array();
    o["fixtures"][0]["shapeType"] = json::String("circle");
    o["fixtures"][0]["radius"] = json::Number(3.f);
    o["fixtures"][0]["friction"] = json::Number(0);
    o["fixtures"][0]["restitution"] = json::Number(0.6);
    o["fixtures"][0]["density"] = json::Number(1);
    o["fixtures"][0]["sensor"] = json::Boolean(false); 
   
    m_obj.load(o); // it should not fail
    m_obj.body()->SetUserData(this);
}

void Ball::update()
{
    assert(m_obj.body() != NULL);
    
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left))
        m_obj.body()->ApplyForce(b2Vec2(-.5f,0.f),m_obj.body()->GetWorldCenter());

    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right))
        m_obj.body()->ApplyForce(b2Vec2(.5f,0.f),m_obj.body()->GetWorldCenter());    
        
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Space))
    {
        b2Vec2 vel = m_obj.body()->GetLinearVelocity();
        if(m_canJump)
        {
            vel.y = 0.f;
            m_obj.body()->SetLinearVelocity(vel);
            m_obj.body()->ApplyLinearImpulse(b2Vec2(0.f,0.2f),m_obj.body()->GetWorldCenter());    
        }
        else if(vel.y > 0.f)
            m_obj.body()->ApplyForce(b2Vec2(0.f,0.2f),m_obj.body()->GetWorldCenter());
    }
    m_shape.setPosition(m_obj.convertPosToSFML());    
    GET_CAMERA.update(m_obj.convertPosToSFML());
}

void Ball::collideWith(Entity &e)
{
    e.collideWith(*this);
}

void Ball::collideWith(Ball &b)
{
}

void Ball::collideWith(Platform &p)
{
    m_canJump = true;
}

void Ball::endCollideWith(Entity& e)
{
    e.endCollideWith(*this);
}

void Ball::endCollideWith(Ball& b)
{
}

void Ball::endCollideWith(Platform& p)
{
    m_canJump = false;
}
                
void Ball::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
    target.draw(m_shape,states);
}


